<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" th:href="@{/layui/css/layui.css}">
    <link rel="stylesheet" th:href="@{/css/custom.form.css}">
</head>
<body>
<div class="layui-fluid">
    <div class="layui-card">
        <div class="panel panel-default operation_user" hidden>
            <div class="panel-heading title"></div>
            <div class="layui-card-body">
                <form class="layui-form " action="" style="width: 700px;margin-top: 10px">
                    <input name="id" lay-reqtext="用户id不能为空" hidden/>
                    <input name="deptId" hidden/>
                    <div class="layui-form-item">
                        <label class="layui-form-label">账号</label>
                        <div class="layui-input-block">
                            <input type="username" name="username" placeholder="请输入账号" autocomplete="off"
                                   lay-verify="required|username"
                                   class="layui-input">
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <div class="layui-form-label ">密码</div>
                        <div class="layui-input-block">
                            <input type="password" name="password" placeholder="请输入密码" autocomplete="off"
                                   lay-verify="required|pass"
                                   class="layui-input">
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <div class="layui-form-label ">手机号</div>
                        <div class="layui-input-block">
                            <input type="phone" name="phone" placeholder="请输入手机号" autocomplete="off" lay-verify="phone"
                                   class="layui-input">
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <div class="layui-form-label ">所属部门</div>
                        <div class="layui-input-block">
                            <input type="deptName" name="deptName" placeholder="请选择所属部门" autocomplete="off"
                                   lay-verify="required"
                                   class="layui-input" readonly="readonly" style="background:#eeeeee!important">
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">状态</label>
                        <div class="layui-input-block">
                            <input type="checkbox" name="status" lay-skin="switch" lay-filter="switch" lay-text="启用|禁用"
                                   checked>
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <div class="layui-input-block">
                            <button type="submit" class="layui-btn" lay-submit="" lay-filter="submit">保存
                            </button>
                            <button class="layui-btn layui-btn-primary" id="btn_cancel">返回</button>
                        </div>
                    </div>
                </form>
            </div>
        </div>
        <div class="user_table_div">
            <div id="searchParam" class="layui-form layui-card-header my-card-header-auto"
                 shiro:hasPermission="sys:user:list">
                <div class="layui-form-item">
                    <div class="layui-inline">
                        <input type="text" id="userId" class="layui-input" autocomplete="off" placeholder="请输入用户ID">
                    </div>
                    <div class="layui-inline">
                        <input type="text" id="username" class="layui-input" autocomplete="off" placeholder="请输入账号">
                    </div>
                    <div class="layui-inline">
                        <input type="text" id="nickName" class="layui-input" autocomplete="off" placeholder="请输入用户昵称">
                    </div>
                    <div class="layui-inline">
                        <input type="text" class="layui-input" id="createTime" placeholder="创建时间">
                    </div>
                    <div class="layui-inline">
                        <select id="status">
                            <option value="">请选择账号状态</option>
                            <option value="1">正常</option>
                            <option value="2">禁用</option>
                        </select>
                    </div>
                    <div class="layui-inline ">
                        <button class="layui-btn" id="search" style="line-height: 100%">查询</button>
                    </div>
                </div>
            </div>
            <div class="layui-card-body">
                <table class="layui-hide" id="user_table" lay-filter="user_table"></table>
                <div class="layui-table-page">
                    <div id="laypage"></div>
                </div>
            </div>
        </div>
        <div id="deptTree" style="display: none"></div>
        <div id="roles" class="demo-transfer" style="display: none"></div>
    </div>
</div>
</body>
<script type="text/html" id="toolbar">
    <div class="layui-btn-container">
        <button type="button" class="layui-btn layui-btn-sm" lay-event="addNewUser" shiro:hasPermission="sys:user:add">
            <i class="layui-icon">&#xe608;</i> 新增用户
        </button>
        <button type="button" class="layui-btn layui-btn-sm" lay-event="batchDeleted"
                shiro:hasPermission="sys:user:delete">
            <i class="layui-icon">&#xe640;</i> 批量删除
        </button>
    </div>
</script>
<script type="text/html" id="tool">
    <a class="layui-btn layui-btn-xs" lay-event="operationRole" shiro:hasPermission="sys:user:role:update">赋予角色</a>
    <a class="layui-btn layui-btn-xs" lay-event="edit" shiro:hasPermission="sys:user:update">编辑</a>
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del" shiro:hasPermission="sys:user:delete">删除</a>
</script>
<script th:src="@{/layui/layui.js}"></script>
<script th:src="@{/js/core.util.js}"></script>
<script>
    layui.use(['jquery', 'table', 'laypage', 'laydate', 'form', 'tree', 'layer', 'transfer'], function () {
        var $ = layui.jquery;
        var table = layui.table;
        var laypage = layui.laypage;
        var form = layui.form;
        var tree = layui.tree;
        var layer = layui.layer;
        var laydate = layui.laydate;
        var transfer = layui.transfer;
        var basePath = CoreUtil.getContextPath();
        var searchParam = {
            pageNum: 1,
            pageSize: 10,
            username: null,
            userId: null,
            status: null,
            startTime: null,
            endTime: null,
            nickName: null
        };
        /*用来记录部门权限树选中*/
        var selectNode = null;

        CoreUtil.sendAjax(basePath + "/api/users", JSON.stringify(searchParam), function (res) {
            //初始化分页器
            laypageTable(res.data.totalRows, searchParam.pageNum);
            //初始化渲染数据
            if (res.data.list != null) {
                loadTable(res.data.list);
            }
        }, "POST", false, function (res) {
            //用户列表接口无权限回调
            layer.msg("抱歉！您暂无获取用户列表的权限");
            var noAuthorityData = [];
            loadTable(noAuthorityData);
        });

        //渲染分页插件
        var laypageTable = function (count, currentPage) {
            laypage.render({
                elem: 'laypage',
                count: count,
                limit: searchParam.pageSize,
                layout: ['prev', 'page', 'next', 'skip', 'limit', 'refresh', 'count'],
                curr: location.hash.replace('#!currentPage=', ''), //获取起始页
                hash: 'currentPage', //自定义hash值
                //连续出现的页码个数
                groups: 3,
                //自定义“上一页”的内容，支持传入普通文本和HTML
                prev: '<i class="layui-icon">&#xe603;</i>',
                //自定义“下一页”的内容，同上
                next: '<i class="layui-icon">&#xe602;</i>',
                jump: function (obj, first) {
                    if (!first) {
                        searchParam.pageNum = obj.curr;
                        searchParam.pageSize = obj.limit;
                        CoreUtil.sendAjax(basePath + "/api/users", JSON.stringify(searchParam), function (res) {
                            if (res.data.list != null) {
                                loadTable(res.data.list);
                                laypageTable(res.data.totalRows, searchParam.pageNum);
                            }
                        }, "POST", false, function (res) {
                            //用户列表接口无权限回调
                            layer.msg("抱歉！您暂无获取用户列表的权限");
                            var noAuthorityData = [];
                            loadTable(noAuthorityData);
                        });
                    }
                }
            });
        };

        //渲染table
        var loadTable = function (data) {
            //展示已知数据
            table.render({
                elem: '#user_table',
                cols: [
                    [
                        {type: 'checkbox', fixed: 'left'},
                        {field: 'id', title: 'ID', width: 300, sort: true},
                        {field: 'username', title: '账号', width: 130},
                        {field: 'phone', title: '手机号', width: 130},
                        {field: 'deptName', title: '所属公司', width: 120},
                        {field: 'realName', title: '真实名称', width: 120},
                        {field: 'nickName', title: '昵称', width: 130},
                        {field: 'email', title: '邮箱', width: 150},
                        {
                            field: 'sex', title: '性别', width: 100, templet: function (item) {
                                if (item.sex === 1) {
                                    return "男";
                                }
                                if (item.sex === 2) {
                                    return "女";
                                }
                            }
                        },
                        {
                            field: 'createTime', title: '创建时间', minWidth: 120, templet: function
                                (item) {
                                return CoreUtil.formattime(item.createTime);
                            }
                        },
                        {
                            field: 'updateTime', title: '更新时间', minWidth: 120, templet: function
                                (item) {
                                return CoreUtil.formattime(item.updateTime);
                            }
                        },
                        {
                            field: 'status', title: '状态', width: 100, templet: function (item) {
                                if (item.status === 1) {
                                    return ' <input type="checkbox" lay-skin="switch" lay-text="正常|禁用" checked disabled>';
                                }
                                if (item.status === 2) {
                                    return ' <input type="checkbox" lay-skin="switch" lay-text="正常|禁用" disabled>';
                                }
                            }
                        },
                        {
                            field: 'createWhere', title: '注册来源', width: 100, templet: function (item) {
                                if (item.createWhere === 1) {
                                    return "Web";
                                }
                                if (item.createWhere === 2) {
                                    return "Android";
                                }
                                if (item.createWhere === 3) {
                                    return "Ios";
                                }
                            }
                        },
                        {width: 300, title: '操作', toolbar: "#tool"}
                    ]
                ],
                data: data,
                even: false,
                limit: data.length,
                limits: [10, 20, 30, 40, 50],
                toolbar: '#toolbar'
            });
        };

        //表头工具栏事件
        var $operationUser = $(".operation_user input[name=status]");
        table.on('toolbar(user_table)', function (obj) {
            switch (obj.event) {
                case 'addNewUser':
                    $(".title").html("新增用户");
                    $(".user_table_div").hide();
                    $(".operation_user").show();
                    var $userId = $(".operation_user input[name=id]");
                    $userId.val("");
                    $userId.removeAttr("lay-verify");
                    $(".operation_user input[name=deptId]").val("");
                    $(".operation_user input[name=username]").val("");
                    var $password = $(".operation_user input[name=password]");
                    $password.val("");
                    $password.attr("lay-verify", "required|pass");
                    $(".operation_user input[name=phone]").val("");
                    $(".operation_user input[name=deptName]").val("");
                    $operationUser.attr('checked', 'checked');
                    $operationUser.attr('type', 'hidden').val(1);
                    var x = document.getElementsByClassName("layui-unselect layui-form-switch");
                    x[0].setAttribute("class", "layui-unselect layui-form-switch layui-form-onswitch");
                    var d = document.getElementsByTagName('em')[0];
                    d.firstChild.nodeValue = '启用';
                    form.render(); //更新全部
                    initTree();
                    break;
                case 'batchDeleted':
                    var checkStatus = table.checkStatus(obj.config.id);
                    var data = checkStatus.data;
                    if (data.length === 0) {
                        layer.msg("请选择要批量删除的用户");
                    } else {
                        var userIds = [];
                        $(data).each(function (index, item) {
                            userIds.push(item.id);
                        });
                        tipDialog(userIds, "选中的");
                    }
                    break;
            }
        });

        //监听指定开关
        form.on('switch(switch)', function () {
            $operationUser.attr('type', 'hidden').val(this.checked ? 1 : 2);
        });

        //编辑或新增的界面取消事件
        $("#btn_cancel").click(function () {
            //显示表格
            $(".user_table_div").show();
            //隐藏编辑窗口
            $(".operation_user").hide();
            //可以防止在表单事件操作后自动刷新
            return false;
        });

        var initTree = function () {
            CoreUtil.sendAjax(basePath + "/api/dept/tree", null, function (res) {
                loadDeptTree(res.data);
            }, "GET", false, function (res) {
                //部门树列表无权限提示
                layer.msg("抱歉！您暂无获取部门树的权限");
                var noAuthorityData = [];
                loadDeptTree(noAuthorityData);
            });
        };

        //加载部门树数据
        var loadDeptTree = function (data) {
            //仅节点左侧图标控制收缩
            tree.render({
                elem: '#deptTree',
                data: data,
                onlyIconControl: true,  //是否仅允许节点左侧图标控制展开收缩
                click: function (obj) {
                    selectNode = obj;
                    layer.msg(JSON.stringify(selectNode.data.title));
                }
            });
        };

        //打开部门树对话框
        $(".operation_user input[name=deptName]").click(function () {
            layer.open({
                type: 1,
                offset: '50px',
                skin: 'layui-layer-molv',
                title: "选择部门",
                area: ['400px', '550px'],
                shade: 0,
                shadeClose: false,
                content: $("#deptTree"),
                btn: ['确定', '取消'],
                yes: function (index) {
                    if (selectNode.data != null) {
                        //选中回显
                        $(".operation_user input[name=deptId]").val(selectNode.data.id);
                        $(".operation_user input[name=deptName]").val(selectNode.data.title);
                    }
                    layer.close(index);
                }
            });
        });

        //表单验证
        form.verify({
            username: function (value) {
                //value：表单的值、item：表单的DOM对象
                if (!new RegExp("^[a-zA-Z0-9_\u4e00-\u9fa5\\s·]+$").test(value)) {
                    return '用户名不能有特殊字符';
                }
                if (/(^\_)|(\__)|(\_+$)/.test(value)) {
                    return '用户名首尾不能出现下划线\'_\'';
                }
                if (/^\d+\d+\d$/.test(value)) {
                    return '用户名不能全为数字';
                }
            },

            //我们既支持上述函数式的方式，也支持下述数组的形式
            //数组的两个值分别代表：[正则匹配、匹配不符时的提示文字]
            pass: [
                /^[\S]{6,12}$/
                , '密码必须6到12位，且不能出现空格'
            ],

            notNullPass: function(value) {
                if (value != null && value !== "" && !(/^[\S]{6,12}$/.test(value))) {
                    return '密码必须6到12位，且不能出现空格';
                }
            },

            phone: function (value) {
                if (value != null && value !== "" && !(/^1[3456789]\d{9}$/.test(value))) {
                    return '请输入正确的手机号';
                }
            }
        });

        //监听提交
        form.on('submit(submit)', function (data) {
            //新增
            if (data.field.id == null || data.field.id === "") {
                CoreUtil.sendAjax(basePath + "/api/user", JSON.stringify(data.field), function (res) {
                    //显示表格
                    $(".user_table_div").show();
                    //隐藏编辑窗口
                    $(".operation_user").hide();
                    $(".layui-laypage-btn").click();
                }, "POST", false, function (res) {
                    //新增用户无权限提示
                    layer.msg("抱歉！您暂无新增用户的权限");
                });
            } else {
                CoreUtil.sendAjax(basePath + "/api/user", JSON.stringify(data.field), function (res) {
                    //显示表格
                    $(".user_table_div").show();
                    //隐藏编辑窗口
                    $(".operation_user").hide();
                    $(".layui-laypage-btn").click();
                }, "PUT", false, function (res) {
                    //更新用户无权限提示
                    layer.msg("抱歉！您暂无编辑用户的权限");
                });
            }
            return false;
        });

        //日期范围
        laydate.render({
            elem: '#createTime',
            type: 'datetime',
            range: '~',
            done: function (value, date, endDate) {
                if (value != null && value !== "") {
                    searchParam.startTime = value.split("~")[0];
                    searchParam.endTime = value.split("~")[1];
                } else {
                    //清空时间的时候要清空以前选择的日期
                    searchParam.startTime = null;
                    searchParam.endTime = null;
                }
            }
        });

        //执行查询
        $("#search").click(function () {
            searchParam.userId = $("#userId").val();
            searchParam.status = $("#status").val();
            searchParam.username = $("#username").val();
            searchParam.nickName = $("#nickName").val();
            searchParam.pageNum = 1;
            CoreUtil.sendAjax(basePath + "/api/users", JSON.stringify(searchParam), function (res) {
                //初始化分页器
                laypageTable(res.data.totalRows, searchParam.pageNum);
                //初始化渲染数据
                if (res.data.list != null) {
                    loadTable(res.data.list);
                }
            }, "POST", false, function (res) {
                //用户列表接口无权限回调
                layer.msg("抱歉！您暂无获取用户列表的权限");
                var noAuthorityData = [];
                loadTable(noAuthorityData);
            });
        });

        //操作工具栏事件
        table.on('tool(user_table)', function (obj) {
            var data = obj.data;
            switch (obj.event) {
                case 'operationRole':
                    CoreUtil.sendAjax(basePath + "/api/user/roles/" + data.id, null, function (res) {
                        initTransfer(res.data);
                        layer.open({
                            type: 1,
                            offset: '50px',
                            skin: 'layui-layer-molv',
                            title: "赋予角色",
                            area: ['500px', '400px'],
                            shade: 0,
                            shadeClose: false,
                            content: $("#roles"),
                            btn: ['确定', '取消'],
                            yes: function (index) {
                                //获得右侧数据
                                var roleIds = [];
                                var getData = transfer.getData('ownData');
                                // layer.msg(JSON.stringify(getData));
                                if (getData.length !== 0) {
                                    $(getData).each(function (index, item) {
                                        roleIds.push(item.value);
                                    });
                                }
                                var param = {
                                    userId: data.id,
                                    roleIds: roleIds
                                };
                                CoreUtil.sendAjax(basePath + "/api/user/roles", JSON.stringify(param), function (res) {
                                    layer.msg(res.msg);
                                    $(".layui-laypage-btn").click();
                                }, "PUT", false, function (res) {
                                    //赋予用户角色无权限提示
                                    layer.msg("抱歉！您暂无赋予用户角色的权限");
                                });
                                layer.close(index);
                            }
                        });
                    }, "GET", false, function (res) {
                        //查询用户角色列表无权限提示
                        layer.msg("抱歉！您暂无查询用户所拥有角色列表的权限");
                    });
                    break;
                case 'edit':
                    $(".user_table_div").hide();
                    $(".operation_user").show();
                    $(".title").html("编辑用户");
                    var $userId = $(".operation_user input[name=id]");
                    $userId.val(data.id);
                    $userId.attr("lay-verify", "required");
                    $(".operation_user input[name=deptId]").val(data.deptId);
                    $(".operation_user input[name=username]").val(data.username);
                    var $password = $(".operation_user input[name=password]");
                    $password.val("");
                    $password.attr("lay-verify", "notNullPass");
                    $(".operation_user input[name=phone]").val(data.phone);
                    $(".operation_user input[name=deptName]").val(data.deptName);
                    var x = document.getElementsByClassName("layui-unselect layui-form-switch");
                    var d = document.getElementsByTagName('em')[0];
                    if (data.status === 1) {
                        $operationUser.attr('checked', 'checked');
                        $operationUser.attr('type', 'hidden').val(1);
                        x[0].setAttribute("class", "layui-unselect layui-form-switch layui-form-onswitch");
                        d.firstChild.nodeValue = '启用';
                    } else {
                        $operationUser.attr('type', 'hidden').removeAttr("checked").val(2);
                        // var x = document.getElementsByClassName("layui-unselect layui-form-switch");
                        x[0].setAttribute("class", "layui-unselect layui-form-switch");
                        // var d = document.getElementsByTagName('em')[0];
                        d.firstChild.nodeValue = '禁用';
                    }
                    form.render(); //更新全部
                    initTree();
                    break;
                case 'del':
                    var userIds = [];
                    userIds.push(data.id);
                    tipDialog(userIds, data.username);
                    break;
            }
        });

        //初始化 赋予角色控件
        var initTransfer = function (data) {
            //显示搜索框
            transfer.render({
                elem: '#roles',
                data: data.allRole,
                title: ['赋予角色', '拥有角色'],
                showSearch: true,
                value: data.ownRoles,
                id: 'ownData',
                parseData: function (res) {
                    return {
                        "value": res.id, //数据值
                        "title": res.name //数据标题
                    }
                }
            })
        };

        //删除前确认对话框
        var tipDialog = function (userIds, username) {
            layer.open({
                content: '确定要删除' + username + "用户么?",
                yes: function (index, layero) {
                    layer.close(index); //如果设定了yes回调，需进行手工关闭
                    CoreUtil.sendAjax(basePath + "/api/user", JSON.stringify(userIds), function (res) {
                        layer.msg(res.msg);
                        $(".layui-laypage-btn").click();
                    }, "DELETE", false, function (res) {
                        //删除用户无权限
                        layer.msg("抱歉！您暂无删除用户的权限");
                    });
                }
            });
        };

    });
</script>
</html>